import { Effect } from 'dva';
import { Reducer } from 'redux';
import {
  readCopyToMe,
  getMyProcessModel,
  // detailForm,
  getFormValue,
  startProcess,
  getMyTaskList,
  getMyProcessList,
  getCopyToMeList,
  getMyTaskCount,
  doTask,
  changeMyApplyProcess,
  urgingProcess,
  getTaskHandler,
  getProcDetail,
  getTaskDetail,
  getHistoryTaskList
} from '@/services/approval';
import _ from 'lodash';
import { IApprovalData, IApprovalItem } from '@/pages/approval/type';
import { IRespCopyData } from './interface-copy';
import { SUCCESS_CODE } from '@/services/constant';
export interface IForm {
  icon?: string;
  procTypeCode: string;
  sort: number;
  procModelName: string;
  procType: string;
  procDefKey: string;
  innerProcDefId: string;
}
export interface IProcess {
  id: string;
  sort: number;
  title: string;
  children: IForm[];
}

// Task
export interface Variable {
  formValues: string;
  formModelData: string;
}

export interface TaskFormData {
  variables: Variable;
  showBusinessKey: boolean;
}

export interface UserTask {
  taskName: string;
  taskStatus: number;
  taskProperty: number;
  handlerName: string;
  taskDefKey: string;
  taskStatusName: string;
  taskRecordId: string;
  innerProcDefId: string;
  procInstId: string;
  handlerComment: string;
  isEndNode: number;
  handlerTime: string;
}

export interface HistoryTask {
  taskName: string;
  taskDefKey: string;
  nodeStatus: number;
  nodeStatusName: string;
  nodeType: number;
  userTasks: UserTask[];
}

export interface IResTaskItem {
  taskDefKey: string; // 流程定义id，用于取当前节点的表单权限
  icon?: string;
  sponsorIcon: string;
  department: string;
  taskName?: string;
  taskStatus?: number;
  taskStatusName?: string;
  taskRecordId: string;
  innerProcDefId: string;
  procInstId: string;
  procNo: string;
  procName: string;
  procStatus: number;
  procStatusName: string;
  crtTime: string;
  historyTask: HistoryTask[];
  formData: TaskFormData;
}

export interface IModelTask {
  srvTime: number;
  status: number;
  data: IResTaskItem[];
  pageNum: number;
  pageSize: number;
  total: number;
}
// task end

// my process 与审批有区别
export interface IMyApplyTaskItem {
  department: string;
  innerProcDefId: string;
  procInstId: string;
  procNo: string;
  procName: string;
  procStatus: number;
  procStatusName: string;
  icon: string;
  sponsor: string;
  sponsorIcon: string;
  sponsorName: string;
  typeName: string;
  procRecordId: string;
  crtTime: string;
  historyTask: HistoryTask[];
  formData: TaskFormData;
}

export interface IMyApplyTask {
  status: number;
  srvTime: number;
  data: IMyApplyTaskItem[];
  pageNum: number;
  pageSize: number;
  count: number;
}
// my process

export interface CApprovalState {
  tabIndex?: string;
  processData?: Array<IProcess>;
  formData?: Record<string, any>;
  taskData?: IModelTask;
  myTaskCount?: number;
  formChange?: number;
  updateProcess?: number;
}
export interface ICApprovalModel {
  namespace: 'capproval';
  state: CApprovalState;
  effects: {
    readCopyToMe: Effect; // 已读未读
    getMyProcessModel: Effect; // 获取申请单
    startProcess: Effect;
    getMyTaskList: Effect;
    getMyProcessList: Effect;
    getMyTaskCount: Effect;
    getCopyToMeList: Effect;
    doTask: Effect;
    changeMyApplyProcess: Effect;
    getFormValue: Effect;
    urgingProcess: Effect;
    getTaskHandler: Effect;
    getProcDetail: Effect;
    getTaskDetail: Effect;
    getHistoryTaskList: Effect;
    formValuesChange: Effect;
  };
  reducers: {
    saveProcessList: Reducer<CApprovalState>;
    saveMyTaskCount: Reducer<CApprovalState>;
    saveFormChangeNum: Reducer<CApprovalState>;
    updateProcess: Effect; // 触发流程组件显示
  };
}

const CApprovalModal: ICApprovalModel = {
  namespace: 'capproval',
  state: {
    processData: [],
    formData: {},
    taskData: undefined,
    updateProcess: 0
  },
  effects: {
    * getHistoryTaskList({ payload }, { call }) {
      const response = yield call(getHistoryTaskList, payload) || {};
      return response;
    },
    * getTaskDetail({ payload }, { call }) {
      const response = yield call(getTaskDetail, payload) || {};
      return response;
    },
    * getProcDetail({ payload }, { call }) {
      const response = yield call(getProcDetail, payload) || {};
      return response;
    },
    * readCopyToMe({ payload }, { call }) {
      yield call(readCopyToMe, payload) || {};
    },
    * getMyProcessModel({ payload }, { call, put }) {
      const response = yield call(getMyProcessModel, payload) || {};
      const { status, data } = response;
      if (status == SUCCESS_CODE) {
        yield put({
          type: 'saveProcessList',
          payload: [...data]
        });
      }
      return response;
    },
    * startProcess({ payload }, { call }) {
      const response = yield call(startProcess, payload) || {};
      return response;
    },
    * getFormValue({ payload }, { call }) {
      const response = yield call(getFormValue, payload) || {};
      return response;
    },
    * getMyProcessList({ payload }, { call }) {
      const response: IMyApplyTask = yield call(getMyProcessList, payload) ||
        {};
      const { status } = response;
      if (status == SUCCESS_CODE && response.data) {
        const arr = response.data.map((el) => {
          const obj: IApprovalItem = { ...el, uid: el.procRecordId };
          return obj;
        });
        0;

        const tmpResp: IApprovalData = {
          ...response,
          data: arr,
          total: response.count
        };
        return tmpResp;
      }
      return null;
    },
    * formValuesChange({ payload }, { put }) {
      yield put({
        type: 'saveFormChangeNum',
        payload: payload
      });
      return null;
    },
    * getMyTaskList({ payload }, { call }) {
      const response: IModelTask = yield call(getMyTaskList, payload) || {};
      const { status } = response;
      if (status == SUCCESS_CODE && response.data) {
        const arr = response.data.map((el) => {
          const obj: IApprovalItem = { ...el, uid: el.taskRecordId };
          return obj;
        });
        const tmpResp: IApprovalData = { ...response, data: arr };
        return tmpResp;
      }
      return null;
    },
    * getCopyToMeList({ payload }, { call }) {
      const response: IRespCopyData = yield call(getCopyToMeList, payload) ||
        {};
      const { status } = response;
      if (status == SUCCESS_CODE && response.data) {
        const arr = response.data.map((el) => {
          const obj: IApprovalItem = { ...el, uid: el.taskRecordId };
          return obj;
        });
        const tmpResp: IApprovalData = { ...response, data: arr };
        return tmpResp;
      }
      return null;
    },
    * getMyTaskCount({ payload }, { call, put }) {
      const response = yield call(getMyTaskCount, payload) || {};
      const { status, data } = response;
      if (status == SUCCESS_CODE) {
        yield put({
          type: 'saveMyTaskCount',
          payload: data
        });
      }
      return null;
    },
    * doTask({ payload }, { call }) {
      const response = yield call(doTask, payload) || {};
      return response;
    },
    * changeMyApplyProcess({ payload }, { call }) {
      const response = yield call(changeMyApplyProcess, payload) || {};
      return response;
    },
    * urgingProcess({ payload }, { call }) {
      const response = yield call(urgingProcess, payload) || {};
      return response;
    },
    * getTaskHandler({ payload }, { call }) {
      const response = yield call(getTaskHandler, payload) || {};
      return response;
    }
  },
  reducers: {
    saveProcessList(state, { payload }) {
      // 把数据处理完成之后再返回
      let result: IProcess[] = [];

      const tmp: IterateAny = {};
      payload = payload || [];
      let sort = 0;
      for (let i = 0; i < payload.length; i++) {
        if (!tmp[payload[i].procTypeCode]) {
          tmp[payload[i].procTypeCode] = [];
          sort++;
        }
        payload[i].sort = sort;
        tmp[payload[i].procTypeCode].push(payload[i]);
      }
      // 分组
      // let tmp = _.groupBy(payload || [], 'procTypeCode');
      for (const key in tmp) {
        const id = key;
        const formarr = tmp[key];
        result.push({
          id,
          title: formarr[0].procType,
          sort: formarr[0].sort,
          children: formarr
        });
      }
      // 排序
      result = _.sortBy(result, (el: any) => Number(el.sort));
      return {
        ...state,
        processData: result
      };
    },
    saveMyTaskCount(state, { payload }) {
      return {
        ...state,
        myTaskCount: payload
      };
    },
    saveFormChangeNum(state, { payload }) {
      return {
        ...state,
        formChange: payload.formChange
      };
    },
    updateProcess(state) {
      return {
        ...state,
        updateProcess: state.updateProcess ? state.updateProcess + 1 : 1
      };
    }
  }
};

export default CApprovalModal;
